#pragma once

#include "Sock.hpp"
#include "Log.hpp"
#include <signal.h>
#include <functional>
class HttpServer
{
public:
    using func_t = std::function<void(int)>;

public:
    HttpServer(const uint16_t &port, func_t func)
        : _port(port), _func(func)
    {
        _listensock = _sock.Socket();
        _sock.Bind(_listensock, _port);
        _sock.Listen(_listensock);
    }
    void start()
    {
        signal(SIGCHLD,SIG_IGN);
        for (;;)
        {
            std::string ClientIp;
            uint16_t ClientPort = 0;
            int sockfd = _sock.Accept(_listensock, &ClientIp, &ClientPort);
            if (sockfd < 0)
            {
                continue;
            }
            if (fork() == 0)
            {
                close(_listensock);
                _func(sockfd);
                close(sockfd);
                exit(0);
            }
            close(sockfd);
        }
    }
    ~HttpServer()
    {
        if(_listensock>=0)
        {
            close(_listensock);
        }
    }

private:
    int _listensock;
    Sock _sock;
    uint16_t _port;
    func_t _func;
};
